package com.pandas.community.service;

import com.pandas.community.Utils.CommunityConstant;
import com.pandas.community.Utils.SensitiveFilter;
import com.pandas.community.dao.CommentMapper;
import com.pandas.community.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentService implements CommunityConstant {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private DiscussPostService discussPostService;

    public List<Comment> selectCommentByEntity(int entityType, int entityId, int offset, int limit){
        return commentMapper.selectCommentByEntity(entityType, entityId, offset, limit);
    }

    public int selectCommentAmount(int entityType, int entityId){
        return commentMapper.selectCommentAmount(entityType, entityId);
    }

    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if(comment == null) throw new IllegalArgumentException("Comment为空！");

        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));

        int rows = commentMapper.addComment(comment);

        // 插入的评论针对帖子
        if(comment.getEntityType() == ENTITY_TYPE_POST){
            int count = commentMapper.selectCommentAmount(ENTITY_TYPE_POST, comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(), count);
        }
        return rows;
    }


    public Comment selectCommentById(int id){
        return commentMapper.selectCommentById(id);
    }

}
